"""
切换句柄
打开新标签
"""

import time
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://baidu.com")
driver.find_element(By.CSS_SELECTOR, "a[href='http://news.baidu.com']").click()
# 打印当前句柄
print(driver.current_window_handle)
# 循环切换，先切换第一个窗口再切换第二个窗口
for handle in driver.window_handles:
    if handle != driver.current_window_handle:  # 如果不是当前句柄就进行切换
        driver.switch_to.window(handle)
        print(handle)

# all_handles=driver.window_handles #获取窗口所有句柄
# driver.switch_to.window(all_handles[1])#根据窗口下标取
time.sleep(3)
# driver.close()
driver.find_element(By.CSS_SELECTOR, "a[href='//help.baidu.com']").click()
# 打开新标签
driver.switch_to.new_window("tab")
driver.get("https://baidu.com")
time.sleep(3)
driver.close()
